<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <input type="file" id="file">
  <script>
    const file = document.querySelector('#file')
    const chunksFun = (file,size = 1024 * 1024) => {
      const chunks = []
      for(let i = 0; i < file.size; i += size) {
        chunks.push(file.slice(i,i + size))
      }
      return chunks
    }
    const uploadFiles = (chunks) => {
      // 批量上传
      const list = []
      for(let i = 0; i < chunks.length; i++) {
          const formdata = new FormData()
          
          formdata.append('index',i)
          formdata.append('filename','虎皮')
          formdata.append('file',chunks[i])
          list.push(fetch('http://127.0.0.1:3000/upload', {
            method: 'POST',
            body: formdata
          }))
      }
      Promise.all(list).then(res => {
        console.log('上传成功')
        // 通知后端合并文件
        fetch('http://127.0.0.1:3000/merge',{
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            fileName: '虎皮'
          })
        })
      })
    }
    file.addEventListener('change',(e) => {
      // file对象底层 继承blob 使用slice切割
      let file = e.target.files[0]
      const chunks = chunksFun(file)
      console.log(file)
      console.log(chunks)
      uploadFiles(chunks)
    })
  </script>
</body>
</html>